import json
from datetime import datetime, timedelta

from django.core.paginator import Paginator
from django.forms.models import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

# Create your views here.
from .models import *
import jwt
def empty(c):
    return c is None or str(c).strip()==''

# @csrf_exempt
# def login(request):
#     if request.method=='POST':
#         data=json.loads(request.body)
#         username=data.get('username')
#         password=data.get('password')
#         if empty(username) or empty(password):
#             return JsonResponse({'msg':'用户名或密码不能为空'},status=400)
#         if user.objects.filter(username=username).exists()==False:
#             return JsonResponse({'msg':'用户名不存在'},status=400)
#         yh=user.objects.get(username=username)
#         if password!=password:
#             return JsonResponse({'msg': '密码错误'}, status=400)
#         # exp_time=datetime.now()+timedelta(minutes=500)
#         # py={'yh':yh.id,'exp':int(exp_time.timestamp())}
#         py={'yh':yh.id}
#         mi='123456'
#         token=jwt.encode(py,mi)
#         return JsonResponse({'msg': '登录成功','token':token},status=200)

# 分类查询
# 登录
@csrf_exempt
def login(request):
    if request.method=='POST':
        data=json.loads(request.body)
        username=data.get('username')
        password=data.get('password')
        if empty(username)or empty(password):
            return JsonResponse({'msg':'账户或密码不能为空'})
        if user.objects.filter(username=username).exists()==False:
            return JsonResponse({'msg': '用户名不存在'})
        yh=user.objects.get(username=username)
        if password!=password:
            return JsonResponse({'msg': '密码错误'})
        exp_time=datetime.now()+timedelta(minutes=120)
        py={'yh':yh.id,'exp':int(exp_time.timestamp())}
        mi='123456'
        token=jwt.encode(py,mi)
        return JsonResponse({'msg': '登录成功','token':token})
def flcategory(request):
       data=category.objects.all()
       list=[]
       for i in data:
           list.append(model_to_dict(i))
       return JsonResponse({
            'msg':'查询成功',
            'data':list
       })
@csrf_exempt
def getlist(request):
    if request.method=='GET':
        data=Book.objects.all()
        total=len(data)
        page=request.GET.get('page',1)
        size=request.GET.get('size','') or 10
        name=request.GET.get('name')
        if name:
            data=data.filter(name__contains=name)
        categorybook_id=request.GET.get('categorybook_id')
        if categorybook_id:
            data=data.filter(categorybook_id=categorybook_id)
        data=Paginator(data,size).get_page(page)
        list=[]
        for i in data:
            list.append(model_to_dict(i))
        return JsonResponse({
            'msg':'查询成功',
            'total':total,
            'data':list
        })
    elif request.method=='POST':
        data=json.loads(request.body)
        Book.objects.create(
            name=data['name'],
            bookid=data['bookid'],
            categorybook_id=data['categorybook_id'],
            price=data['price'],
            num=data['num']
        )
        return JsonResponse({'msg':'添加成功'})

@csrf_exempt
def updata_delete(request,id):
    xg=Book.objects.get(id=id)
    if request.method=='PUT':
        try:
            data = json.loads(request.body)
            xg.name = data['name']
            xg.bookid = data['bookid']
            xg.categorybook_id = data['categorybook_id']
            xg.price = data['price']
            xg.num = data['num']
            xg.save()
        except Exception as e:
            return JsonResponse(e)
        return JsonResponse({
            'msg':'修改成功',
            'data':model_to_dict(xg)
        })
    elif request.method=='DELETE':
        if empty(id):
            return JsonResponse({'msg':'不能为空'})
        if Book.objects.filter(id=id).exists():
            if Book.objects.filter(categorybook_id=id).exists():
                return JsonResponse({'msg':'书已被借阅，不能被删除'})
            Book.objects.get(id=id).delete()
            return JsonResponse({'msg':'删除成功'})
        return JsonResponse({'msg': '该数据不存在,无法删除'})
    elif request.method=='GET':
        data = Book.objects.get(id=id)
        return JsonResponse({'data':model_to_dict(data)})
# ④图书‌借阅、借阅记录查询接口‌（多表关联）‌
# 借阅操作同步减少图书库存
# 分页、条件查询(和前端对应)
# @csrf_exempt
# def pageselect(request):
#     if request.method=='POST':
#         data=json.loads(request.body)
#         number=data['number']
#         id=data['booname_id']
#         book=Book.objects.get(id=id)
#         tj=borrow.objects.create(
#             number=number,
#             peopel=data['peopel'],
#             gh_time=datetime.now()+timedelta(days=30),
#             sj_time=datetime.now()+timedelta(days=10),
#             bookname_id=id
#         )
#         book.num=(book.num-int(number))
#         book.save()
#         return JsonResponse({'msg':'借阅成功','data':model_to_dict(tj)})
#     elif request.method=='GET':
#         data=borrow.objects.all()
#         page=request.GET.get('page',1)
#         size=request.GET.get('size') or 10
#         name=request.GET.get('name','')
#         if name:
#             data=data.filter(bookname__contains=name)
#         data=Paginator(data,size).get_page(page)
#         list=[]
#         for i in data:
#             list.append(model_to_dict(i))
#         return JsonResponse({
#                  'msg':'查询成功',
#                  'data':list
#         })

@csrf_exempt
def pageselect(request):
    if request.method=='POST':
        data=json.loads(request.body)
        number=data['number']
        id=data['bookname_id']
        book=Book.objects.get(id=id)
        tj=borrow.objects.create(
            number=number,
            peopel=data['people'],
            # 应归还时间
            gh_time=datetime.now() + timedelta(days=30),
            # 实际归还时间
            sj_time=datetime.now() + timedelta(days=40),
            bookname_id=id
        )
        book.num=(book.num-int(number))
        book.save()
        return JsonResponse({'msg':'借阅成功','data':model_to_dict(tj)})
    elif request.method=='GET':
        data=borrow.objects.all()
        page=request.GET.get('page') or 1
        size=request.GET.get('size') or 2
        name=request.GET.get('name')
        if name:
            data=data.filter(bookname__icontains=name)
        data=Paginator(data,size).get_page(page)
        list=[]
        for i in data:
            list.append(model_to_dict(i))
        return JsonResponse({
            'msg':'查询成功',
            'data':list
        })



# @csrf_exempt
# def getlist(request):
#     if request.method=='GET':
#         data=Book.objects.all()
#         total=len(data)
#         page=request.GET.get('page',1)
#         size=request.GET.get('size','') or 10
#         name=request.GET.get('name','')
#         bookid=request.GET.get('bookid','')
#         if name:
#             data=data.get(name__contains=name)
#         if bookid:
#             data=data.get(bookid=bookid)
#         data=Paginator(data,size).get_page(page)
#         list=[]
#         for i in data:
#             list.append(model_to_dict(i))
#         return JsonResponse({
#             'msg': '查询成功',
#             'data': list,
#             'total':total
#         })
#     elif request.method=='POST':
#         data=json.loads(request.body)
#         Book.objects.create(
#             name=data['name'],
#             bookid=data['bookid'],
#             categorybook_id=data['categorybook_id'],
#             price=data['price'],
#             num=data['num']
#         )
#         return JsonResponse({
#             'msg':'添加成功'
#         })
#
# @csrf_exempt
# def updata_delete(request,id):
#     xg=Book.objects.get(id=id)
#     if request.method=='PUT':
#        data=json.loads(request.body)
#        xg.name=data['name']
#        xg.bookid=data['bookid']
#        xg.categorybook_id=data['categorybook_id']
#        xg.price=data['price']
#        xg.num=data['num']
#        xg.save()
#
#        return JsonResponse({
#            'msg':'修改成功',
#            'data':model_to_dict(xg)
#        })
#     elif request.method=='DELETE':
#
#         if empty(id):
#             return JsonResponse({'msg':'该数据为空'})
#         if Book.objects.filter(id=id).exists():
#            if Book.objects.filter(categorybook_id=id).exists():
#                return JsonResponse({'msg':'该书已被借阅，无法删除'})
#            Book.objects.get(id=id).delete()
#            return JsonResponse({'msg':'删除成功'})
#         return JsonResponse({'msg':'删除失败，该数据不存在'})





